package com.leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Date250331 {
    public static void main(String[] args) {
     int[] nums ={0,0,4,-2,-3,-2,-2,-3};
     List<List<Integer>> ret = fourSum(nums, -1);
        System.out.println(ret);
    }
    public static List<List<Integer>> fourSum(int[] nums, int target) {
        Arrays.sort(nums);
        int n = nums.length;
        //int left = 0, right = n - 1;
        List<List<Integer>> ret = new ArrayList<>();
        for(int i = 0; i < n;){
            for(int j = i + 1; j< n;){
                int left = j + 1, right = n -1;
                while(left < right){
                    if(nums[i] + nums[j] + nums[left] + nums[right] > target){
                        right--;
                    }else if(nums[i] + nums[j] + nums[left] + nums[right] < target){
                        left++;
                    }else{
                        ret.add(new ArrayList<>(Arrays.asList(nums[i],nums[j],nums[left],nums[right])));
                        left++;
                        right--;
                        if(left < right && nums[left] == nums[left-1]){
                            left++;
                        }
                        if(left < right && nums[right] == nums[right+1]){
                            right--;
                        }
                    }
                }
                j++;
                while(j < n&& nums[j] == nums[j-1]){
                    j++;
                }
            }
            i++;
            while(i < n && nums[i] == nums[i -1] ){
                i++;
            }
        }
        return ret;
    }

}
